﻿using System.Collections.Generic;
using UnityEngine;

namespace HKTools
{
    [ExecuteInEditMode]
    public class HK_TipLine : MonoBehaviour
    {
#if UNITY_EDITOR
        LineRenderer lineRenderer;

        Transform title_TF;

        public List<Transform> linePos_List;

        void Start()
        {
            ResetLinPos();
        }

        void OnValidate()
        {
            ResetLinPos();
        }

        void Update()
        {
            if (Application.isPlaying)
                return;

            if (transform.childCount != linePos_List.Count)
            {
                ResetLinPos();
            }

            UpdateLineRendererPositions();
        }

        void ResetLinPos()
        {
            if (lineRenderer == null)
                lineRenderer = GetComponent<LineRenderer>();

            title_TF = transform.parent.Find("Title");

            linePos_List = new List<Transform>();

            for (int i = 0; i < transform.childCount; i++)
            {
                linePos_List.Add(transform.GetChild(i));
            }
        }


        void UpdateLineRendererPositions()
        {
            if (linePos_List == null || linePos_List.Count == 0)
                return;

            Vector3[] linePoses = new Vector3[linePos_List.Count];

            for (int i = 0; i < linePos_List.Count; i++)
            {
                linePoses[i] = linePos_List[i].localPosition;
            }

            if (lineRenderer == null)
                lineRenderer = GetComponent<LineRenderer>();

            lineRenderer.positionCount = linePos_List.Count;
            lineRenderer.SetPositions(linePoses);

            title_TF.position = linePos_List[linePos_List.Count - 1].position + Vector3.up * 0.2f;
        }
#endif
    }
}